/*
 * (C) Copyright 2001
 * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
 *
 * SPDX-License-Identifier:	GPL-2.0+
 */

/*
 * Date & Time support for Philips PCF8563 RTC
 */

/* #define	DEBUG	*/

#include <stdint.h>
#include "i2c_master.h"
#include "RealTimeClock.h"

#define CONFIG_SYS_I2C_RTC_ADDR	0xA2

static uint8_t rtc_read  (uint8_t reg);
static void  rtc_write (uint8_t reg, uint8_t val);

/* ------------------------------------------------------------------------- */

void rtc_get (TimeBCD *tmp)
{
	uint8_t sec, min, hour, mday, wday, mon_cent, year;

	sec	= rtc_read (0x02);
	min	= rtc_read (0x03);
	hour	= rtc_read (0x04);
	mday	= rtc_read (0x05);
	wday	= rtc_read (0x06);
	mon_cent= rtc_read (0x07);
	year	= rtc_read (0x08);


	tmp->bcd_sec  =  (sec  & 0x7F);
	tmp->bcd_min  =  (min  & 0x7F);
	tmp->bcd_hour =  (hour & 0x3F);
	tmp->bcd_mday =  (mday & 0x3F);
	tmp->bcd_mon  =  (mon_cent & 0x1F);
	tmp->bcd_year =  (year);
	tmp->bcd_wday =  (wday & 0x07);

}

void rtc_set (TimeBCD *tmp)
{
	uint8_t century;

	rtc_write (0x08, (tmp->bcd_year % 100));

	century = 0;
	rtc_write (0x07, (tmp->bcd_mon) | century);

	rtc_write (0x06, (tmp->bcd_wday));
	rtc_write (0x05, (tmp->bcd_mday));
	rtc_write (0x04, (tmp->bcd_hour));
	rtc_write (0x03, (tmp->bcd_min ));
	rtc_write (0x02, (tmp->bcd_sec ));

}

void rtc_reset (void)
{
	/* clear all control & status registers */
	rtc_write (0x00, 0x00);
	rtc_write (0x01, 0x00);
	rtc_write (0x0D, 0x00);

	/* clear Voltage Low bit */
	rtc_write (0x02, rtc_read (0x02) & 0x7F);

	/* reset all alarms */
	rtc_write (0x09, 0x00);
	rtc_write (0x0A, 0x00);
	rtc_write (0x0B, 0x00);
	rtc_write (0x0C, 0x00);
}

static const RealTimeClock pcf8563Clock = {
	.setBcd = rtc_set,
	.getBcd = rtc_get,
};



void PCF8563_Init(void)
{
	i2c2_init();
	RealTimeClock_Register(&pcf8563Clock);
}


/* ------------------------------------------------------------------------- */

static uint8_t rtc_read (uint8_t reg)
{
	uint8_t val = 0;
	i2c2_readReg(CONFIG_SYS_I2C_RTC_ADDR, reg, &val, 1);
	return val;
}

static void rtc_write (uint8_t reg, uint8_t val)
{
	//i2c_reg_write (CONFIG_SYS_I2C_RTC_ADDR, reg, val);
	i2c2_writeReg(CONFIG_SYS_I2C_RTC_ADDR, reg, &val, 1);
}


